package com.home.service;

import com.home.entity.Hr;
import com.home.entity.HrRole;
import com.home.mapper.HrMapper;
import com.home.mapper.HrRoleMapper;
import com.home.mapper.RoleMapper;
import com.home.util.HrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class HrService implements UserDetailsService {

    @Autowired
    private HrMapper hrMapper;

    @Autowired
    private HrRoleMapper hrRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Hr hr = hrMapper.loadUserByUsername(username);
        if (hr == null) {
            throw new UsernameNotFoundException("用户名不存在！");
        }
        hr.setRoles(hrMapper.getHrRolesById(hr.getId()));
        return hr;
    }

    public List<Hr> getAllHr(String keywords) {
        return hrMapper.getAllHrEXCurrentHr(HrUtils.getCurrentUser().getId(), keywords);
    }


    public Integer updateHr(Hr hr) {
        return hrMapper.updateByPrimaryKeySelective(hr);
    }

    @Transactional
    public boolean updateHrWithRole(Integer hrid, Integer[] rids) {
        hrRoleMapper.deleteByHrId(hrid);
        return hrRoleMapper.addRoles(hrid, rids) == rids.length;
    }

    @Transactional
    public boolean deleteHrById(Integer id) {
        List<HrRole> lists = hrRoleMapper.getAllHrWithRole(id);
        if (lists != null) {
            hrRoleMapper.deleteByHrId(id);
        }
        int i = hrMapper.deleteByPrimaryKey(id);
        if (i == 1) {
            return true;
        } else {
            return false;
        }
    }
}
